<?php
session_start();

// 函数：检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 当前用户
$currentUser = $_SESSION['username'] ?? null;
$targetUserId = $_GET['id'] ?? null;

// 验证登录状态和目标用户
if (!$currentUser) {
    die(json_encode(['status' => 'error', 'message' => '用户未登录！']));
}

if (!$targetUserId) {
    die(json_encode(['status' => 'error', 'message' => '未指定好友！']));
}

// 加载好友关系文件
$friendFile = __DIR__ . '/ffile.json';
$friendConfig = ensureFile($friendFile);

// 验证当前用户是否有权限删除这个好友关系
$isFriend = isset($friendConfig[$currentUser]) && in_array($targetUserId, $friendConfig[$currentUser]);
$isFriendOf = isset($friendConfig[$targetUserId]) && in_array($currentUser, $friendConfig[$targetUserId]);

if (!$isFriend && !$isFriendOf) {
    die(json_encode(['status' => 'error', 'message' => '你们不是好友关系！']));
}

// 从双方的好友列表中删除彼此
if (isset($friendConfig[$currentUser])) {
    $friendConfig[$currentUser] = array_filter($friendConfig[$currentUser], function($friend) use ($targetUserId) {
        return $friend !== $targetUserId;
    });
    // 重新索引数组
    $friendConfig[$currentUser] = array_values($friendConfig[$currentUser]);
}

if (isset($friendConfig[$targetUserId])) {
    $friendConfig[$targetUserId] = array_filter($friendConfig[$targetUserId], function($friend) use ($currentUser) {
        return $friend !== $currentUser;
    });
    $friendConfig[$targetUserId] = array_values($friendConfig[$targetUserId]);
}

// 保存更新后的好友关系
file_put_contents($friendFile, json_encode($friendConfig, JSON_UNESCAPED_UNICODE));

// 删除用户主页文件中的好友记录
$userChatsFile = __DIR__ . "/user/{$currentUser}/chats.json";
if (file_exists($userChatsFile)) {
    $chats = json_decode(file_get_contents($userChatsFile), true);
    // 过滤掉被删除的好友
    $chats = array_filter($chats, function($chat) use ($targetUserId) {
        return $chat['id'] !== $targetUserId;
    });
    // 重新索引数组
    $chats = array_values($chats);
    file_put_contents($userChatsFile, json_encode($chats, JSON_UNESCAPED_UNICODE));
}

// 删除对方用户主页文件中的好友记录（如果存在）


// 删除聊天记录文件
$sharedChatFile1 = __DIR__ . "/messages/shared_chats/{$currentUser}_{$targetUserId}.json";
$sharedChatFile2 = __DIR__ . "/messages/shared_chats/{$targetUserId}_{$currentUser}.json";
if (file_exists($sharedChatFile1)) {
    unlink($sharedChatFile1);
}
if (file_exists($sharedChatFile2)) {
    unlink($sharedChatFile2);
}

echo json_encode(['status' => 'success', 'message' => '好友已删除']);
?>